package models

import (
	"blog/configs"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var db *gorm.DB

func init() {
	// 建立连接
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", configs.DbUser, configs.DbPwd, configs.DbHost, configs.DbPort, configs.DbName)
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	if configs.DEBUG {
		db = db.Debug()
	}
	// 自动迁移
	if err = db.AutoMigrate(new(Tag), new(Column), new(Article), new(Admin)); err != nil {
		panic(err)
	}
	// 初始化专栏
	var count int64
	if err = db.Find(new(Column)).Count(&count).Error; err != nil {
		panic(err)
	}
	if count == 0 {
		if err = db.Save(&Column{
			Id:   1,
			Name: "默认",
			Nums: 0,
		}).Error; err != nil {
			panic(err)
		}
	}
	// 初始化管理员
	if err = db.Find(new(Admin)).Count(&count).Error; err != nil {
		panic(err)
	}
	if count == 0 {
		if err = db.Save(&Admin{
			Name:  "kkkunny",
			Email: "kkkunny@qq.com",
			Image: "",
		}).Error; err != nil {
			panic(err)
		}
	}
}
